package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"store/models"
	"store/pkg"
	"strconv"
	"time"
)

type StoreController struct {
	beego.Controller
}

func (c *StoreController) Add() {
	name := c.GetString("name")
	types := c.GetString("types")
	tel := c.GetString("tel")
	address := c.GetString("address")
	var sto = models.Store{
		Name:    name,
		Types:   types,
		Tel:     tel,
		Address: address,
	}
	err := models.DB.Create(&sto).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
}

func (c *StoreController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Store{}).Count(&count)
	offset := (page - 1) * size
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	var stos []models.Store
	var pageDate = make(map[string]interface{})
	key := "store-" + strconv.Itoa(page)
	val, err := models.Rds.Get(key).Result()
	if err != nil {
		err = models.DB.Model(&models.Store{}).Offset(offset).Limit(size).Find(&stos).Error
		if err != nil {
			c.Data["json"] = models.JsonR{
				Code: 500,
				Msg:  "列表展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		pageDate["page"] = page
		pageDate["size"] = size
		pageDate["count"] = count
		pageDate["stos"] = stos
		pageDate["sumpage"] = sumpage
		xx, _ := json.Marshal(&pageDate)
		value := string(xx)
		models.Rds.Set(key, value, time.Second*5)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "列表展示成功-mysql",
			Data: pageDate,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &pageDate)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "列表展示成功-redis",
			Data: pageDate,
		}
		c.ServeJSON()
	}

}

func (c *StoreController) Login() {
	user := c.GetString("user")
	password := c.GetString("password")
	var users models.User
	err := models.DB.Model(&models.User{}).Where("user=?", user).First(&users).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "账号不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if users.Password == pkg.Md5pwd(password) {
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "登录成功",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "密码输入错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

}
